import levinCommon
#import wineAreas

from world.worldArea  import Area, WorldArea, RegionArea, CountryArea, AppellationArea, GroupAppellationArea
from world.bottle import Bottle
import world.areaUtils as areaUtils

from kivy.app import App
from kivy.uix.widget import Widget

from kivyext.treegridview import TreeView, TreeViewLabel, TreeViewNode, ScrollableHeaderTreeView
#from kivyext.mylabel import MyLabel

from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout

import guiCommon
from guiCommon import LeVinTreeLabel

#Window.clearcolor = (1,1,1,1)

from kivy.uix.label import Label
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty

class LeVinWindowStyle(Widget):
    clearcolor = ListProperty([1,1,1,1])


class LeVinCountryLabel(LeVinTreeLabel):
    pass
class LeVinRegionLabel(LeVinTreeLabel):
    pass


from kivy.lang import Builder

guiCommon.load_kv_file('levintreeview.kv')

Window.clearcolor = (1,1,1,1)#LeVinWindowStyle.clearcolor


wineCollumns= ['appellation','cru_name','millesime', 'meanrate']
wineCollumnsTitle= [_('Appellation'), _('Cru name'), _('Vintage'), _("Rate")]
NCOLS = len(wineCollumns)

class LeVinAreaNode(TreeViewNode):

    def re_init(self):
        super(LeVinAreaNode,self).__init__(self)
        self.row_span = [0,NCOLS]
        classLabel = LeVinRegionLabel if isinstance(self, RegionArea) else LeVinCountryLabel
        n = self.localname
        self.columns = [classLabel(text=n if n else self.name,halign='center') ]
        self.computeVisibility()
        
    def computeVisibility(self):
        self.is_visible = len(self.wines) >0 or any( a.is_visible for a in self.subAreas() )


    def postSelectionVisibility(self,forceVisible = False):
        """Recusrively Compute and set visibility according to the _isSelected of each area """
        selResult = self._isSelected
        for a in self.subAreas():
            v=a.postSelectionVisibility()
            selResult = selResult or v
        self.is_visible = selResult or forceVisible
        return selResult
        
        

from guiTheme import ColorTheme

class LeVinBottleNode(TreeViewNode):
    def re_init(self):
        super(LeVinBottleNode,self).__init__(self)
        c = ColorTheme.green if self.color == 1 else ColorTheme.purple2
        self.columns = [ LeVinTreeLabel(text=unicode(getattr(self,att))) for att in wineCollumns[:3] ]+[ LeVinTreeLabel(text= self.rateStr() ) ]
        for w in self.columns:
            w.color=c
        
    def rateStr(self):
        return '-' if self.meanrate is None else str(self.meanrate)

    def update_widget(self):
        for (w, att) in zip(self.columns, wineCollumns)[:-1]:
            w.text = unicode(getattr(self,att))
        self.columns[-1].text = self.rateStr()
        #self.is_visible = 
        
## ---------------------------------------
# IMPORTANT -----------------------------
# Dynamically modify the world hierarchy base class so they ALSO represent 
# widgets in the UI
# this allows to save the world/user hierarchy independently of the widget system
# and then to add the widget system on the hierarchy when UI is needed.
Area.__bases__ = (LeVinAreaNode,) + Area.__bases__

Bottle.__bases__ = (LeVinBottleNode,)+Bottle.__bases__ 
## ---------------------------------------



ScrollableHeaderTreeView.DefaultWidClass = LeVinTreeLabel

theTree = ScrollableHeaderTreeView(size = Window.size, size_hint = (1,1) , num_columns = NCOLS, spacing_x=2,show_slider = True,
                                   columns_width_force=[ None,None,0.12, 0.09],
                                   header_content = wineCollumnsTitle,
                                   hide_header = False,
                                   )
#theTree.setDebugOn(False)



# - -------------------------------------------
# redefine the WorldArea add/removeWine, so widgets are also handled
def addWine_widget(self,bottle):
    self.addWine_original(bottle)
    reg = bottle.parentArea.getRegionOrAbove()
    country = reg.getCountry()
    #print 'uuup',reg.name, country.name , self.nodes
    if country not in self.nodes:
        #print ' ---- Adding Country', country.name
        country.re_init()
        theTree.add_node(country, parent = self)        
    if reg not in country.nodes and reg != country:
        #print ' ---- Adding Region', reg.name
        reg.re_init()
        theTree.add_node(reg, parent = country)
    bottle.re_init()    
    theTree.add_node(bottle, parent = reg)
    country.updateSelector()
            
def removeWine_widget(self, bottle):
    self.removeWine_original(bottle)
    area = bottle.parentArea
    hierarchy = area.areaInheritance()
    #reg=bottle.parentArea.getRegionOrAbove()
    bottle.tastings = []
    theTree.remove_node(bottle)
    for topA in hierarchy:
        topA.computeVisibility()

WorldArea.addWine_original = WorldArea.addWine
WorldArea.addWine = addWine_widget
WorldArea.removeWine_original = WorldArea.removeWine
WorldArea.removeWine = removeWine_widget
# - -------------------------------------------

from guiCommon import LeVinButton, CompactLabel, LeVinAlert

def delete_bottle(ev, bottle):
    al = LeVinAlert( title=_('Suppress Wine %s'%(bottle.cru_name,)),
                     validText=_("Do suppress") ,
                     cancelText=_("Do NOT suppress"),
                     alertText= _('Please confirm suppression'),                     
                     )
    al.cancelB.bind(on_release = al.dismiss)

    def _remove(*l):
        levinCommon.wineWorld.removeWine(bottle)
        al.dismiss()
    al.validB.bind(on_release = _remove )
    al.open()



guiCommon.commonEvents.bind(on_delete_bottle = delete_bottle)    

## def delete_bottle(ev, tasting):
##     pass
    

def addRegionNode(self):
    if self.parentArea :
        theTree.add_node(self,parent = self.parentArea)
    for w in self.wines:
        theTree.add_node(w,parent= self)

def addAppellationNode(self):
    reg = self.getRegionOrAbove()
    if reg :
        for w in self.wines:
            theTree.add_node(w,parent= reg)
    

_addnodeFunc = {
    WorldArea : addRegionNode,
    CountryArea : addRegionNode,
    RegionArea : addRegionNode,
    AppellationArea : addAppellationNode,
    GroupAppellationArea : addAppellationNode    

    }

def _addNode(self):
    _addnodeFunc[self.__class__ ]( self)

def initWidgets():
    """This function is called once.
    It sets up the widget part of the hierarchy"""

    levinCommon.wineWorld.countNWines()
    # init the widget part of the wine hiearchy (set labels, colors...)
    #  For areas :
    levinCommon.wineWorld.doOnSubAreas( LeVinAreaNode.re_init)
    #  For wines :
    for b in levinCommon.wineWorld.getWines():
        b.re_init()
    
    levinCommon.wineWorld.doOnSubAreas( LeVinAreaNode.computeVisibility)
    levinCommon.wineWorld.doOnSubAreas( _addNode )
    theTree._root = levinCommon.wineWorld
    theTree._root.setup(theTree)
    theTree.indent_level = 0
    theTree.hide_root = True
    guiCommon.commonEvents.bind(on_bottle_edited= checkBottleAgainstSelectors)


def checkBottleAgainstSelectors(dummy,bottle):
    levinCommon.wineWorld.isBottleSelected(bottle)



def newSelectedWines(self, allwines):
    for w in allwines:
        w.is_visible = True
        w.parentArea._isSelected = True
    levinCommon.wineWorld.postSelectionVisibility(forceVisible=True)
    guiCommon.commonEvents.visibleWines = len(allwines)
    guiCommon.commonEvents.visibleBottles = sum(w.numInStock for w in allwines if w.numInStock>-1)
    print ' New one selectected ', len(allwines)    
    guiCommon.commonEvents.dispatch("on_wineselect_update", allwines)
    print '   -> dispatched on_wineselect_update'
Area.newSelectedWines = newSelectedWines
